package com.qi.spzx.manager.listener;

import cn.hutool.core.collection.ListUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.qi.spzx.manager.mapper.CategoryMapper;
import com.qi.spzx.model.vo.product.CategoryExcelVo;
import org.apache.poi.ss.formula.functions.T;

import java.util.List;

/**
 * @Description 监听器
 * @Author dingchunlin
 * @Date 2024/2/23 13:55
 * @Version 1.0.0
 */
public class ExcelListener<T> implements ReadListener<T> {

    private static final int BATCH_COUNT = 100;

    private List<T> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    //构造mapper,操作数据库
    private CategoryMapper categoryMapper;

    public ExcelListener(CategoryMapper categoryMapper){
        this.categoryMapper = categoryMapper;
    }

    /**
     * 从第二行开始读取，把每行数据封装到T对象里面
     * @param t
     * @param analysisContext
     */
    @Override
    public void invoke(T t, AnalysisContext analysisContext) {
        //把每行数据对象T放到List集合里面
        cachedDataList.add(t);
        //如果数据达到了100，就要进行存储
        if (cachedDataList.size() >= BATCH_COUNT){
            //调用方法批量添加到数据库
            saveData();
            //清除缓存
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }



    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
    }

    /**
     * 保存的方法
     */
    private void saveData() {
        categoryMapper.batchInsert((List<CategoryExcelVo>)cachedDataList);
    }

}
